﻿namespace PillBox.Client.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;
    using PillBox.Client.Framework;
    using PillBox.Client.Model;

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class ScheduleViewModel : ViewModelBase
    {
        private long _personID;

        public ScheduleViewModel()
        {
        }

        public string Title
        {
            get;
            set;
        }

        public string ColorBand
        {
            get;
            set;
        }

        public IList<ScheduleDayViewModel> Schedules
        {
            get;
            private set;
        }

        public void WithSchedule(long personID)
        {
            this._personID = personID;
        }

        public void GoBack()
        {
            ResultEnumerator.Begin(Show.Screen<HomeViewModel>());
        }

        public override void Activate()
        {
            ResultEnumerator.Begin(this.LoadSchedule());
        }

        private IEnumerable<IResult> LoadSchedule()
        {
            if (this._personID > 0)
            {
                var personQuery = new GetPeopleQuery
                {
                    Filter = p => p.PersonID == this._personID
                }.AsResult();

                yield return personQuery;

                this.Title = personQuery.Response.First().Name;
                this.ColorBand = personQuery.Response.First().ColorBand;
            }
            else
            {
                this.Title = "All";
                this.ColorBand = String.Empty;
            }

            RaisePropertyChanged(() => Title);
            RaisePropertyChanged(() => ColorBand);

            var query = new GetScheduleQuery
            {
                PersonID = this._personID,
                Date = DateTime.Today
            }.AsResult();

            yield return query;

            this.Schedules = query.Response.OrderBy(x => x.Date).ToList();

            RaisePropertyChanged(() => Schedules);
        }
    }
}